<?php
/**
 * Created by PhpStorm.
 * User: 68008000
 * Date: 2017/11/13
 * Time: 21:04
 */

namespace app\common\model;




use houdunwang\arr\Arr;
use think\Db;
use think\Loader;
use think\Model;

class Category extends Model
{
    //连接数据库
    protected $table= 'caregory';
    protected $pk= 'cid';
    //添加父级数据
    public function  add($data)
    {
        //判断是否输入数据
        $validate = Loader::validate('Caregory');
        if(!$validate->check($data)){
            return ['valid'=>0,'msg'=>$validate->getError()];
        }
        //添加数据
        $result=Db::table('category')
            ->data(['cname' =>$data['cname'], 'pid' => $data['pid'],'ctitle'=>$data['ctitle'],'cdes'=>$data['cdes'],'ckeywords'=>$data['ckeywords'],'csort'=>$data['csort']])
            ->insert();
        if($result){
            return ['valid'=>1,'msg'=>'添加成功'];
        }else{
            // 验证失败 输出错误信息
          return ['valid'=>0,'msg'=>$this->getError()];
        }
    }
   //主页获取分类的数据
    public function CateData()
    {
        $data = db('category')->order('cid desc')->select();
        $treeData=Arr::tree($data,'cname','cid','pid');
        return $treeData;
    }
    //编辑
    public function edit($data){
       p($data);die;
    }
    //获取父级子级的cname
    public function getCname($cid){
        $cids = $this->getSon(db('category')->select(),$cid);
        $cids[]=$cid;
        //删除获取的数据
        $cateData = db('category')->whereNotIn('cid',$cids)->select();
        //树状删除后的数据
        return Arr::tree($cateData,'cname');
    }
    //遍历获取子级的cname
    public function getSon($data,$cid)
    {
        //循环遍历数据获取数据
        static $temp = [];//静态保存
        foreach ($data as $k=>$v){
            if($v['pid'] == $cid){
                $temp[] = $v['cid'];
                //递归
                $this->getSon($data,$v['cid']);
            }
        }
        return $temp;
    }
    //删除
    public function del($cid){
        //1.通过当前要删除的数据的cid获取当前数据的pid
        $pid = db('category')->where('cid',$cid)->value('pid');
        //2.修改子集的pid 改成父级的pid
        $this->where('pid',$cid)->update(['pid'=>$pid]);
        //3.删除当前这条数据
        $res = Category::destroy($cid);
        if ($res){
            return ['valid'=>1,'msg'=>'删除成功'];
        }else{
            return ['valid'=>0,'msg'=>'删除失败'];
        }
    }

}